<script setup lang="ts">
import CdlTable from "@/components/table";
import type {TableTree} from "@/interfaces/components/Table";
import type {Task, WayBill} from "@/interfaces/views/task/task";
import CdlSearch from "@/components/search";
import CdlForm from "@/components/form";
import type {FormTree} from "@/interfaces/components/Form";
import type {Query, Request, State, FormData, Mode} from "@/interfaces/components/Page";
import {reactive, h} from "vue";
import {useTablePagingTemplate} from "@/hooks/TableHooks";
import {useRouter} from "vue-router";
import {createPopup} from "@/utils/createPopup";
import {useTaskAssociationDriverApi, useTaskWayBillApi} from "@/api/project/task";
import {cloneDeep} from "lodash";
import {ElMessage} from "element-plus"
import {mergeObjects} from "@/utils/utilities";
import {appStore} from "@/store/modules/app";

const router = useRouter()
const store = appStore()

const request: Request ={
  createdIsNeed: true,
  url: "/project/task",
  responseProcessing: responsePreprocessing
}

const searTree: FormTree<Task> = [
  [
    {component: "select", options: store.getDict("task_state"),
      optionProps: {
        label: "dictLabel", value: "dictValue"
      }, prop: "state", label: "任务状态"},
  ]
]
const TaskTabTree: TableTree<Task> = {
  colRule: [
    {type: "expand", prop: "waybills", slot: (scope: WayBill[]) =>{
        return h(CdlTable, {
          templateTree: wayBillTabTree,
          data: scope,
          controlFixed: true,
          controlWidth: 100
        })}, minWidth: 40},
    {ti: "任务名称", prop: "name", width: 200},
    // {ti: "关联车辆", format: (scope: Task) =>{
    //     return scope.cars.length.toString() + "辆" || "无"
    //   }},
    {ti: "关联司机", width: 200, format: (scope: Task) =>{
        if(scope.cars.length === 0) return "无"
        let str = ""
        for(let i = 0; i < scope.cars.length; i++){
          if(scope.cars[i]?.captain) str = scope.cars[i]?.driverName
        }
        return `队长：${(str? str : scope.cars[0]?.driverName)};等${scope.cars.length}人`
      }},
    {ti: "任务状态", prop: "state", dict: "task_state"},
    {ti: "所属订单", prop: "projectName", width: 150, tooltip: true},
    {ti: "开始日期", prop: "startTime", minWidth: 160},
    {ti: "结束日期", prop: "endTime", minWidth: 160},
    {ti: "运单数", format: (data)=> {
        return data.waybills?.length || 0
      }},
    {ti: "创建人"},
    {ti: "备注"},
  ],
  control: [
    {name: "详情", type: "info", prop: "id", method: jumpTaskDetails, auth: "project:task:info"},
    {name: "轨迹分析", type: "primary", method: ()=>{}, auth: "project:task:analyse"},
    {name: "新建运单", type: "primary", method: openCreateWaybillInsert, auth: "project:task:save"},
  ],
}
const wayBillTabTree: TableTree<WayBill> = {
  colRule: [
    {ti: "运单编号", prop: "id", minWidth: 180},
    {ti: "运单类型", prop: "type", dict: "waybill_type"},
    {ti: "运单状态", prop: "state", dict: "waybill_state"},
    {ti: "关联车辆", prop: "car", minWidth: 180},
    {ti: "关联司机", prop: "driverName"},
    {ti: "创建人", prop: "createName"},
    {ti: "接单时间", prop: "startTime", minWidth: 160},
    {ti: "完成时间", prop: "endTime", minWidth: 160},
    {ti: "时间告警", prop: ""},
    {ti: "是否结算", prop: ""},
    {ti: "备注", prop: "remark"},
  ],
  control: [
    {name: "详情", type: "info", prop: "id", method: openWayBillDetails, auth: "project:task:info"},
    // {name: "轨迹分析", type: "primary", method: ()=>{}, auth: "project:task:analyse"},
    // {name: "编辑", type: "success", method: openCreateWayBillUpdate, auth: "project:task:update"},
  ]
}
const wayBillFormTree: FormTree<WayBill> = [
    [
      {label: "关联任务", component: "input", prop: "taskName", disabled: true},
    ],
  [
    {label: "关联司机", component: "select", prop: "taskCarId", serviceOptionKey: "associationDriver",
      optionProps: {label: "name", value: "id"}
      , rule:[{
        required: true, message: '关联司机不能为空', trigger: 'blur'
      }]},
    {label: "创建人", component: "input", prop: "createName", disabled: true},
  ],
  [
    {label: "接单时间", component: "datePicker", prop: "startTime", type: "datetime", rule:[{
        required: true, message: '接单时间不能为空', trigger: 'blur'
      }]},
    {label: "完成时间", component: "datePicker", prop: "endTime", type: "datetime", rule:[{
        required: true, message: '完成时间不能为空', trigger: 'blur'
      }]}
  ],
    [
      {label: "备注", component: "input", type: "textarea", prop: "remark", style: "width: 100%"},
    ]
]
const wayBillFormData: FormData<WayBill> = {
  taskId: "",
  taskCarId: "",
  startTime: "",
  endTime: "",
  createName: "",
  remark: ""
}
/**
 * 打开新建运单
 * @param data
 */
function openCreateWaybillInsert(data:Task){
  createPopup("新建运单", h(CdlForm, {
    templateTree: wayBillFormTree,
    model: createFormDataTemplate(data, "add"),
    init: {associationDriver: ()=> getAssociationDriver(data.id)}
  }), "add", popupCallBack)
}

function openCreateWayBillUpdate(data:WayBill){
  createPopup("编辑运单", h(CdlForm, {
    templateTree: wayBillFormTree,
    model: createFormDataTemplate(data, "update"),
    init: {associationDriver: ()=> getAssociationDriver(data.taskId)}
  }), "add", popupCallBack)
}
/**
 * 运单详情
 * @param id
 */
function openWayBillDetails(id: number | string){
  router.push({
    path: "/projectManage/task/waybillDetails",
    query: {
      id: id
    }
  })
}
/**
 * 创建表单之前的数据预处理
 * @param data
 * @param mode
 */
function createFormDataTemplate(data: Task | WayBill, mode: "add" | "update"){
  let obj = cloneDeep(wayBillFormData)
  if(mode === "add"){
    obj.taskName = (data as Task).name
    obj.taskId = (data as Task).id
  }else {
    mergeObjects(obj, data)
  }
  return obj
}
/**
 * 响应预处理
 * @param data
 */
function responsePreprocessing(data: Task[]){
  for (const task of data) {
    const cars = task.cars
    if(cars.length === 0) continue
    task.waybills.forEach((waybill: WayBill) =>{
      const car = cars.find(car => car.id === waybill.taskCarId)
      if(car){
        waybill.driverName = car.driverName
        waybill.car = car.car
      }
    })
  }
}
function jumpTaskDetails(id: string | number){
  router.push({
    path: "/projectManage/task/taskDetails",
    query: {
      id: id
    }
  })
}
/**
 * 获取任务关联的司机列表
 * @param id 任务id
 */
function getAssociationDriver(id:string){
  return new Promise((resolve, reject) => {
    useTaskAssociationDriverApi(id).then(res =>{
      resolve(res.data)
    })
  })
}
/**
 * 弹出层回调
 * @param data 数据
 * @param mode 模式
 */
function popupCallBack(mode: Mode, data?: any){
  switch (mode) {
    case "add":
      useTaskWayBillApi(data).then((res:any) =>{
        if(!res.code) {
          ElMessage.success('新增成功')
          query()
        }
      })
          break
    case "update":
          break
    case "search":
      query(data)
          break
    case "resetting":
      query()
          break
  }
}

/**
 * 跳转任务新增
 */
function jumpTaskInsert(){
  router.push({
    path: "/projectManage/task/createAndModifyTask"
  })
}

const taskState = reactive<State<Query<Task>, Task>>({
  queryForm: {},
  dataList: []
})
const {query, handleSizeChange, handleCurrentChange, loading} = useTablePagingTemplate(request, taskState)
</script>

<template>
<el-card>
  <CdlSearch :model="taskState.queryForm" :template-tree="searTree" @submit="popupCallBack">
    <template #menu>
      <el-button type="primary" @click="jumpTaskInsert" v-auth="'project:task:save'">新建任务</el-button>
    </template>
  </CdlSearch>
  <CdlTable :data="taskState.dataList" :template-tree="TaskTabTree"
            :control-width="300" border :loading="loading" controlFixed></CdlTable>
  <el-pagination
      :current-page="taskState.page"
      :page-sizes="taskState.pageSizes!"
      :page-size="taskState.limit"
      :total="taskState.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  ></el-pagination>
</el-card>
</template>


